package com.ex.mzwqz.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.ex.mzwqz.model.UserEntity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * Created by 夏国强 on 2016/3/19.
 */
public class SharePrefenceUtils {


        public static void saveUser(Context context, UserEntity user){
            SharedPreferences preferences = context.getSharedPreferences("base64",
                    Context.MODE_PRIVATE);
            // 创建字节输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                // 创建对象输出流，并封装字节流
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                // 将对象写入字节流
                oos.writeObject(user);
                // 将字节流编码成base64的字符窜
                String oAuth_Base64 = new String(Base64.encode(baos
                        .toByteArray(),Base64.DEFAULT));
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("USER", oAuth_Base64);

                editor.commit();
            } catch (IOException e) {
                Log.i("xia","1111");
            }
        }

        public static UserEntity getUser(Context context){
            UserEntity user = null;
            SharedPreferences preferences = context.getSharedPreferences("base64",
                    Context.MODE_PRIVATE);
            String productBase64 = preferences.getString("USER", "");

            if(TextUtils.isEmpty(productBase64))
                return null;
            //读取字节
            byte[] base64 = Base64.decode(productBase64.getBytes(),Base64.DEFAULT);

            //封装到字节流
            ByteArrayInputStream bais = new ByteArrayInputStream(base64);
            try {
                //再次封装
                ObjectInputStream bis = new ObjectInputStream(bais);
                try {
                    //读取对象
                    user = (UserEntity) bis.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return user;
        }
}
